<?php
/**
 * 文件上传&下载
 *
 * @package     controller
 * @author      Akon(番茄红了) <aultoale@gmail.com>
 * @copyright   Copyright (c) 2008 (http://www.imeelee.com)
 * @license     http://www.gnu.org/licenses/gpl.html     GPL 3
 */
class FileController extends Ext_Controller_Action
{

    /**
     * 初始化方法
     */
    public function init()
    {
    }

    /**
     * 上传文件列表
     */
    public function browseAction()
    {
        $this->view->title = '上传文件列表';
        $this->view->config = $this->config->upload;
        $this->view->files = EGP_Io::scan($this->config->upload->basePath);
    }

    /**
     * 文件上传
     */
    public function uploadAction()
    {
        $this->view->title = '文件上传';
        if ($this->request->isPost()) {
            $config = $this->config->upload;
            $config->savePath = $config->basePath;
            unset($config->basePath);
            $upload = new EGP_File_Upload($config);
            $result = $upload->save($this->request->getFiles('file'));
            if ($result === false) {
                $this->view->feedback(array(
                    'message'  => '上传失败：' . $upload->getMessage()
                ));
            }
            $result = $upload->getResult();
            echo "<h1>上传成功！</h1>";
            var_dump($result);
        }
    }

    /**
     * 文件下载
     */
    public function downloadAction()
    {
        $filename = $this->config->upload->basePath . DIR_SEP . $this->request->getQuery('filename');

        if (!is_readable($filename)) {
            $this->view->feedback(array(
                'title'    => '发生错误',
                'message'  => '指定的文件不存在或者已经被删除',
                'redirect' => $this->request->getServer('HTTP_REFERER', '/'),
                'linktext' => '点击继续',
            ));
        }

        $this->view = null;
        header('Content-Description: File Transfer');
        header('Content-Type: application/force-download');
        header('Content-Length: ' . filesize($filename));
        header('Content-Disposition: attachment; filename=' . basename($filename));
        readfile($filename);
    }

    /**
     * 文件删除
     */
    public function deleteAction()
    {
        @unlink($this->config->upload->basePath . DIR_SEP . $this->request->getQuery('filename'));
        $this->redirect($this->url(array('action' => 'browse'), true));
    }

}